<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2021/1/18  14:57
 */

namespace App\Services\Api;

use App\Models\DiscountMeal;
use App\Models\DiscountInfo;
use App\Models\ClassBaseInfo;
use App\Models\UserCoupon;
use App\Services\Api\UserIntegralServices;
use App\Models\DiscountOrder;
use Illuminate\Support\Facades\DB;
use App\Traits\RetrunService;


class DiscountService
{

    public function dicount_list()
    {
        //return DiscountMeal::paginate(15);
        //dd($data);
        /*    if(count($data['data']) >0){
                foreach ($data['data'] as $k=>$v){
                    //dd($v);

                }
            }*/
        return DiscountMeal::where('meal_day', '!=', 0)->where('is_enable','1')->paginate(15);
    }

    public function discount_info($discount_id)
    {
        return DiscountMeal::where('id', $discount_id)->first();
    }

    public function buy_discount($discount_id, $user_id)
    {
        DB::beginTransaction();
        try {
            $integralApi = new \App\Services\Api\UserIntegralServices();
            $discountObj = DiscountMeal::where('id', $discount_id)->first();

            if (empty($discountObj->id)) throw new \Exception('请传discount_id');

            if (empty($discountObj->meal_day)) throw new \Exception('捆绑卷没设置有效期');

            $discount_price = $discountObj->discount_price;

            if ($integralApi->available_integral($user_id) < $discount_price) {
                throw new \Exception('积分不足');
            };

            $userCoupon = [];

            $class_info_ids = DiscountInfo::where('discount_id', $discount_id)->pluck('class_info_id')->toArray();
            $class_info = ClassBaseInfo::whereIn('id', $class_info_ids)->select([
                'id',
                'class_base_id',
                'store_id',
            ])
                ->with([
                    'class_base' => function ($q) {
                        $q->select(['id', 'class_price', 'class_name']);
                    },
                ])
                ->get()
                ->toArray();

            //记录该预约id的拼接的字符，用来排查是否能用该捆绑卷
            $class_base_info_id = array_column($class_info,'id');

            $order['user_id'] = $user_id;
            $order['user_coupon_id'] = 0;
            $order['created_at'] = date("Y-m-d H:i:s");
            $order['discount_id'] = $discount_id;
            $order['discount_json'] = json_encode($class_base_info_id);
            $order['discount_price'] = $discountObj->original_price;
            $order['discount_title'] = $discountObj->discount_name;
            $order['order_sn'] = getOrder();
            $order['discount_expired'] = date("Y-m-d H:i:s",strtotime("+{$discountObj->meal_day} day"));
            $order['discount_cove'] = DB::table('discount_meal')->where('id',$discount_id)->value('cove');

            $discount_order_id = (new DiscountOrder)->insertGetId($order);

            if (count($class_info) > 0) {
                foreach ($class_info as $k => $v) {
                    //dd($v);
                    $userCoupon[$k]['user_id'] = $user_id;
                    $userCoupon[$k]['store_id'] = $v['store_id'];
                    //$userCoupon[$k]['store_id'] =
                    $userCoupon[$k]['type'] = 2;
                    $userCoupon[$k]['status'] = 1;
                    $userCoupon[$k]['remarks'] = '捆绑销售现金券' . '-' . $v['class_base']['class_name'];
                    $userCoupon[$k]['class_base_info_id'] = $v['id'];
                    $userCoupon[$k]['is_expiration'] = 2;
                    $userCoupon[$k]['discount_id'] = $discount_id;

                    //strtotime('+10 day');
                    //$userCoupon[$k]['expiration_time'] =
                    $userCoupon[$k]['coupon_value'] = $v['class_base']['class_price'];
                    $userCoupon[$k]['created_at'] = date("Y-m-d H:i:s");
                    $userCoupon[$k]['discount_order_id'] = $discount_order_id;
                }
            }

            //dd($userCoupon);
            UserCoupon::insert($userCoupon);

            //dd($discount_price);

            //扣减积分
            $integralApi = new \App\Services\Api\UserIntegralServices();

            $use_integral_msg = [
                '购买捆绑销售',
                $discountObj->class_title,
                "-{$discount_price}分",
                date("Y-m-d"),
            ];

            //扣减积分
            $msg = implode("/",$use_integral_msg);

            $is_use = $integralApi->use_integral(auth('api')->user()->id, $discount_price, $msg);

            if (!$is_use) {
                //return self::fail('扣款失败');
                throw new \Exception('扣款失败');
            }

            DB::commit();

            return ['bool' => true];

        } catch (\Exception $e) {
            DB::rollBack();

            return ['message' => $e->getMessage(), 'bool' => false];
        }

    }

}
